from absl import app, flags
import pandas as pd

from coin.support.proto_log.logic.util import enumerate_sub_log_into_subinfos
from coin.base.datetime_util import convert_string_to_dates
from coin.exchange.base.subscription_logger import parse_file_name
from coin.support.market_quotes.logic.constants import TICKER_CHECK_LIST
from xunkemgmt_client.tool.slack_noti import send_to_slack


FLAGS = flags.FLAGS


def _check_log_not_archived(sub_info_from_archive):
  diff = []
  mea_check_list = [tuple(mea.split('.')) for mea in TICKER_CHECK_LIST]
  sub_info_set = set([(sub_info.market_type, sub_info.exchange, sub_info.api_version) for sub_info
                      in sub_info_from_archive])
  for mea_info in mea_check_list:
    if mea_info not in sub_info_set:
      diff.append(dict(zip(('market_type', 'exchange', 'api_version'), mea_info)))
  diff_msg = ''
  if len(diff) != 0:
    diff_df = pd.DataFrame(diff)
    diff_msg = '\nSub proto log not archived:\n' + \
               diff_df.sort_values(by=['market_type', 'exchange']).to_string()
  return diff_msg


def _check_log_not_registered(sub_info_from_archive):
  diff = []
  mea_check_list = [tuple(mea.split('.')) for mea in TICKER_CHECK_LIST]
  for sub_info in sub_info_from_archive:
    if (sub_info.market_type, sub_info.exchange, sub_info.api_version) not in mea_check_list:
      diff.append({'market_type': sub_info.market_type,
                   'exchange':sub_info.exchange,
                   'api_version': sub_info.api_version})
  diff_msg = ''
  if len(diff) != 0:
    diff_df = pd.DataFrame(diff)
    diff_msg = '\nSub proto log not registered:\n' + \
               diff_df.sort_values(by=['market_type', 'exchange']).to_string()
  return diff_msg


def _check_archive(trading_date, root_dir, slack_receiver):
  td_str = trading_date.strftime('%Y%m%d')
  sub_log_from_archive = enumerate_sub_log_into_subinfos(
      root_dir, td_str, parse_file_name)
  msg = f'{root_dir}:\n'
  msg += '%s' % _check_log_not_archived(sub_log_from_archive)
  msg += '%s' % _check_log_not_registered(sub_log_from_archive)
  if slack_receiver is not None:
    msg = '```' + msg + '```'
    send_to_slack(msg, slack_receiver, 'msg')


def main(_):
  assert FLAGS.trading_date
  trading_date = convert_string_to_dates(FLAGS.trading_date)[0]
  _check_archive(trading_date, FLAGS.root_dir, FLAGS.slack_receiver)


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'Trading date in form of %Y%m%d.')

  flags.DEFINE_string('root_dir', '/remote/iosg/strat-1/buckets/log.raw.coin/live//sub_proto_log', '')

  flags.DEFINE_string('slack_receiver', None, 'slack_receiver')
  
  app.run(main)
